// ; (function (global, undefined) {
//   var plugin = {
//     add: function (n1, n2) {

//     }
//   }
//   'plugin' in global && global.plugin == plugin;

// })(window);

; (function (undefined) {
  "use strict"
  let _global;
  let npmEnv = process.env.NODE_ENV || 'production';//development or production

  const SNSAPI_BASE = 'snsapi_base';//静默授权(不弹出授权页面，直接跳转，只能获取用户openid)
  const SNSAPI_USERINFO = 'snsapi_userinfo';//网页授权(弹出授权页面，可通过openid拿到昵称、性别、所在地。并且， 即使在未关注的情况下，只要用户授权，也能获取其信息 )
  const snsScope = SNSAPI_BASE;//授权方式

  const blkCommunityAppId = 'wxace96c7b75d050e4';//prod 布洛克社区
  const blkAssistantAppId = 'wx81e9d5a1b52d0bad';//dev  布洛克小助手
  const APPID = npmEnv == 'development' ? blkAssistantAppId : blkCommunityAppId;
  
  /**
 * Get user id
 */
  function getUserIdByCode(code) {
    axios.get('/wxauthcallback?code=' + code).then(res => {
      if (res.data.error != 0) {
        alert(res.data && res.data.msg || '接口出错');
        return;
      } 
      let data = res.data.data;

      setCookie('bountyHunter_id', data.id);  // 记录用户id 兼容微信
      setCookie('cookiekey', data.cookiekey);  // 记录用户id 兼容微信
      localStorage.setItem('bountyHunter_id', data.id); // 记录用户id 兼容公信宝 
      localStorage.setItem('cookiekey',data.cookiekey);// 记录用户cookiekey 兼容公信宝 
      localStorage.setItem('cookiekey_expires', new Date().getTime());// 记录用户cookiekey过期时间 兼容公信宝  
    }).catch(err => {
      console.log('wxauth err',err)
      // alert('wxauth err:' + JSON.stringify(err));
    })
  }

  function generateUrl(params) {
    let query = 'https://open.weixin.qq.com/connect/oauth2/authorize?';
    for (let key in params) {
      query += key + '=' + params[key] + '&'
    }
    query = query.substr(0, query.length - 1) + '#wechat_redirect'
    return query;
  }

  function getUrlParams(param) {
    let reg = new RegExp("(^|&)" + param + "=([^&]*)(&|$)");
    let local = window.location;
    let r = local.search.substr(1).match(reg);
    if (r != null)
      return decodeURI(r[2]);//对encodeURI编码处理过的uri进行解码
    return null;
  }

  /**
  * Get code by appid and else params
  */
  function getCodeFromWx() {
    let redirectUrl = window.location.href;
    let params = {
      appid: APPID,
      redirect_uri: encodeURIComponent(redirectUrl),
      response_type: 'code',
      scope: snsScope,
      state: 'BOUNTY',
    }

    let url = generateUrl(params);
    localStorage.setItem("auth url:",url)
    window.location.href = url;  
  }

  //读取cookies 
  function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg)) 
      return unescape(arr[2]);
    else
      return null;
  }

  //写cookies
  function setCookie(name, value) {
    var Days = 3;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
  }

  function WxPlugin() { }

  /**
   * 页面加载后进行授权判断
   */
  function pageLoadCheckCode() {
    let code = getUrlParams('code')
    let cookieKey = getCookie('cookiekey');
    if (!cookieKey || cookieKey == 'undefined') {
      if (!code) {
        getCodeFromWx();
      } else{
        getUserIdByCode(code);
      }
    }
  }

  WxPlugin.prototype.pageLoadCheckCode = pageLoadCheckCode
  WxPlugin.prototype.getUrlParams = getUrlParams


  // 最后将插件对象暴露给全局对象
  _global = (function () { return this || (0, eval)('this'); }());
  if (typeof module !== "undefined" && module.exports) {
    module.exports = WxPlugin;
  }
  if (typeof define === "function" && define.amd) {
    define(function () { return WxPlugin; });
  }
  !('WxPlugin' in _global) && (_global.WxPlugin = WxPlugin);
}());
